package com.example.demo.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.nio.ByteBuffer;

public class MyServer {
      /*
     第六次课 网络编程
     服务端serverSocketChannel
     实际通信 socketChannel


    * */

    public static void main(String[] args) throws IOException {
        //1、创建socket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2、设置服务端监听端口
        serverSocketChannel.bind(new InetSocketAddress(8000));
        List<SocketChannel> channelList = new ArrayList<>();

        //3、接收客户端连接
        ByteBuffer buffer = ByteBuffer.allocate(20);
        while (true) {
            System.out.println("等待连接服务器...");
            SocketChannel socketChannel = serverSocketChannel.accept();//阻塞 程序等待client
            System.out.println("服务器已经连接..." + socketChannel);
            channelList.add(socketChannel);
            //client与服务端的通信过程 NIO代码
            for (SocketChannel channel : channelList) {
                System.out.println("开始实际的数据通信....");
                channel.read(buffer);//阻塞 对应的IO通信的阻塞
                buffer.flip();
                CharBuffer decode = StandardCharsets.UTF_8.decode(buffer);
                System.out.println("decode.toString() = " + decode.toString());
                buffer.clear();
                System.out.println("通信已经结束....");
            }
        }
    }

    /*上面两种 出现了两种阻塞等待
    * 阻塞1：serverSocketChannel.accept()
    * 阻塞2：channel.read(buffer)
    *
    *
    *
    * */




}
